package com.wishwall.web.filters;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;

import com.wishwall.auth.DeviceContext;
import com.wishwall.exceptions.WishWallException;
import com.wishwall.persistence.PersistenceContext;
import com.wishwall.web.utils.RequestHelper;

/**
 * 
 * @author yavor.gologanov
 *
 */
public class DeviceSecurityFilter extends AbstractFilter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
			throws IOException, ServletException {
		
		try {
			HttpServletRequest httpRequest = (HttpServletRequest) request;
			
			PersistenceContext persistenceContext = RequestHelper.getPersistenceContext(request);
			String userAgent = httpRequest.getHeader("User-Agent");
			String deviceUid = httpRequest.getHeader("From");
			
			DeviceContext deviceContext = DeviceContext.createDeviceContext(persistenceContext, userAgent, deviceUid);
			RequestHelper.setDeviceContext(httpRequest, deviceContext);
			
			doNextFilter(request, response, chain);
		}
		catch (WishWallException e) {
			response.setContentType(MediaType.APPLICATION_JSON);
			((HttpServletResponse) response).getWriter().write(e.getMessage());
			((HttpServletResponse) response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		}		
	}
		
	
}
